package com.bank.service;


import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.bank.domain.Customer;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.bank.service.GenerateCardService;

@Service("customerService")
@Transactional
public class CustomerService {

	protected static Logger logger = Logger.getLogger("service");
	
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;

	@Resource(name="generateCardService")
	private GenerateCardService generateCardService;
	
	@Resource(name="pdfService")
	private PdfService pdfService;
	
	/**
	 * Retrieves all customers
	 * 
	 * @return a list of customers
	 */
	@SuppressWarnings("unchecked")
	public List<Customer> getAll() { 
		logger.debug("Retrieving all customer");
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		// Create a Hibernate query (HQL)
		Query query = session.createQuery(" FROM Customer");
		// Retrieve all
		return  query.list();
	}

	/**
	 * Retrieves a single customer
	 */

	public Customer get( Integer id ) {
		Session session = sessionFactory.getCurrentSession();
		return (Customer) session.get(Customer.class, id);
	}

	/**
	 * Retrieves a single customer ID
	 */	
	public int getCurrentId(){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createSQLQuery("SELECT CUSTOMER_ID FROM customers" + " WHERE CLIENT_NUMBER='"+auth.getName()+"'");
		try {
			String stringID = query.uniqueResult().toString();
	    	return Integer.parseInt(stringID);
		} catch (Exception e) {
			return 0;
		}
	}
	
	
	public String add(Customer customer) {
		logger.debug("Adding new customer");
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		customer.setActive(1);
		customer.setRoleId(1);
		java.util.Date today = new java.util.Date();
		customer.setDateCreated(new java.sql.Date(today.getTime()));
		customer.setDateModified(new java.sql.Timestamp(today.getTime()));
		customer.setBlocked(0);
		customer.setClientNumber(generateCardService.getNumber());
		
		// Persists to db
		session.save(customer);
		session.refresh(customer);
		List <String> codes = generateCardService.saveCardNumbers(customer.getCustomerId());
		String fileName = pdfService.createPDF(customer.getClientNumber(), customer.getName(), customer.getSurname(), customer.getEmail(), codes);		
		return fileName;
	}
	
	public int getRandomCode(){
		int rand = ThreadLocalRandom.current().nextInt(1,50);
		return rand;
		//return 33;
	}
	
	public Boolean checkCode(int codeNumber, String value){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createSQLQuery("SELECT CUSTOMER_CODE_VALUE FROM customer_codes" + " WHERE CUSTOMER_ID='"+this.getCurrentId()+"' AND CUSTOMER_CODE_NUMBER='" + codeNumber + "'");
		try {
			String stringID = query.uniqueResult().toString();
	    	if(stringID.trim().equals(value.trim())){
	    		return true;
	    	}
	    	else{
	    		return false;
	    	}
	    	
		} catch (Exception e) {
			return false;
		}
	}	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public boolean createTaskSession(String taskHash, int taskTtl){
		Session session = sessionFactory.getCurrentSession();
		String userSession = RequestContextHolder.currentRequestAttributes().getSessionId();
		int sessionTtl = taskTtl;
		Query newQuery = session.createSQLQuery("INSERT INTO sessions ( TASK_ID , TASK_HASH , USER_SESSION , SESSION_STARTED, SESSION_TTL ) VALUES ( NULL , '" + taskHash + "', '" + userSession + "', CURRENT_TIMESTAMP, " + sessionTtl + ")" );
		System.out.println("Query is: " + newQuery);
		newQuery.executeUpdate();
		return true;
	}		

	public boolean checkTaskSession(String taskHash){
		Session session = sessionFactory.getCurrentSession();
		String userSession = RequestContextHolder.currentRequestAttributes().getSessionId();
		Query query = session.createSQLQuery("SELECT TASK_ID FROM sessions" + " WHERE TASK_HASH='"+taskHash+"' AND USER_SESSION='" + userSession + "' AND (SESSION_STARTED + INTERVAL 360 SECOND) > current_timestamp");
		System.out.println("Vaicajums: " + query);
		try {
			Object results = query.uniqueResult();
			if(results != null){
				return true;
			}
			else{
				return false;
			}
	    	
		} catch (Exception e) {
			return false;
		}
	}
	
}
